
local skynet = require "skynet"

local TIMER = {}


local timer_num  = 0

INVALID_TIMER = -1

TIMER.__index = TIMER 

function TIMER.new(...)
    local o =  {}
    setmetatable(o,TIMER)
    TIMER.init(o, ...)
    return o
end 

function TIMER:init()

    self.timer_mgr = {}
    self.id        = 0
end


-- interval 定时器时间   count 执行次数 -1表示无限次  func 执行函数
function TIMER:add(interval, count, func )

    self.id = self.id + 1
    local id = self.id 
    local timer = {interval = math.ceil(interval), count = count, func = func}
    self.timer_mgr[id] = timer
    skynet.timeout(timer.interval, function () self:on_timer(id) end)
    timer_num = timer_num + 1 
    return id 
end


-- 执行代码操作
function TIMER:on_timer(id)

    local timer = self.timer_mgr[id]

    if not timer then 
        return 
    end 

    if timer.count > 0 then 
        timer.count = timer.count - 1 
    end 

    -- 如果时 count = -1 则时无限次 
    if timer.count ~= 0 then

        skynet.timeout(timer.interval,function () self:on_timer(id) end)
    end 

    timer.func()
end  

-- 获取定时器
function TIMER:get(id)

    if id then 
        return self.timer_mgr[id] 
    end 
end 

-- 移除定时器
function TIMER:remove(id)

    if id < 0 then   
        return 
    end 

    if id then 
        self.timer_mgr[id] = nil
        timer_num = timer_num - 1 
    end 
end 

return TIMER

